package cn.yunhe.controller;

import cn.yunhe.model.Transaction;
import cn.yunhe.validate.TransactionValidator;
import org.springframework.stereotype.Controller;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by zs on 2017/12/18.
 */
@Controller
@RequestMapping("/validate")
public class TransactionController {

    @RequestMapping("validator")
    public ModelAndView validate(@Valid Transaction tran, Errors errors) {
        //是否错误
        if (errors.hasErrors()) {
            List<FieldError> errorList = errors.getFieldErrors();
            for (FieldError f : errorList) {
                System.out.println("属性：" + f.getField() + ",信息：" + f.getDefaultMessage());
            }
        }

        ModelAndView mv = new ModelAndView("redirect:/validate.jsp");
        return mv;
    }

    @InitBinder
    public void initBinder(DataBinder binder) {
        //将验证器绑定到控制器
        binder.setValidator(new TransactionValidator());
    }


}
